<template>
  <div class="other-page">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-breadcrumb separator="/" style="margin-bottom: 20px;">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>其他工具</el-breadcrumb-item>
        </el-breadcrumb>
        <h2 style="margin-bottom: 20px; color: #303133;">其他工具</h2>
      </el-col>
    </el-row>

    <el-tabs v-model="activeTab" type="card">
      <!-- 正则表达式验证 -->
      <el-tab-pane label="正则表达式验证" name="regex">
        <el-card>
          <el-form :model="regexForm" label-width="120px">
            <el-form-item label="正则表达式">
              <el-input
                v-model="regexForm.pattern"
                placeholder="请输入正则表达式，如: ^[a-zA-Z0-9]+$"
                @input="testRegex"
              />
            </el-form-item>
            <el-form-item label="测试文本">
              <el-input
                v-model="regexForm.testText"
                type="textarea"
                :rows="4"
                placeholder="请输入要测试的文本"
                @input="testRegex"
              />
            </el-form-item>
            <el-form-item label="匹配选项">
              <el-checkbox-group v-model="regexForm.flags" @change="testRegex">
                <el-checkbox label="g">全局匹配 (g)</el-checkbox>
                <el-checkbox label="i">忽略大小写 (i)</el-checkbox>
                <el-checkbox label="m">多行匹配 (m)</el-checkbox>
                <el-checkbox label="s">点号匹配换行 (s)</el-checkbox>
                <el-checkbox label="u">Unicode (u)</el-checkbox>
                <el-checkbox label="y">粘性匹配 (y)</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="测试结果">
              <el-input
                v-model="regexForm.result"
                type="textarea"
                :rows="6"
                readonly
                placeholder="测试结果将在这里显示"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testRegex">测试匹配</el-button>
              <el-button @click="clearRegex">清空</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 颜色值转换 -->
      <el-tab-pane label="颜色值转换" name="color">
        <el-card>
          <el-form :model="colorForm" label-width="120px">
            <el-form-item label="输入颜色">
              <el-input
                v-model="colorForm.input"
                placeholder="请输入颜色值，支持HEX、RGB、HSL等格式"
                @input="convertColor"
              >
                <template #append>
                  <el-color-picker v-model="colorForm.colorPicker" @change="onColorPickerChange" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="颜色预览">
              <div style="display: flex; align-items: center; gap: 10px;">
                <div 
                  :style="{ 
                    width: '50px', 
                    height: '50px', 
                    backgroundColor: colorForm.hex || '#ffffff',
                    border: '1px solid #dcdfe6',
                    borderRadius: '4px'
                  }"
                ></div>
                <span>{{ colorForm.hex || '无颜色' }}</span>
              </div>
            </el-form-item>
            <el-form-item label="转换结果">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="HEX">
                    <el-input v-model="colorForm.hex" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="RGB">
                    <el-input v-model="colorForm.rgb" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="HSL">
                    <el-input v-model="colorForm.hsl" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="CMYK">
                    <el-input v-model="colorForm.cmyk" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyColorValue('hex')">复制HEX</el-button>
              <el-button type="primary" @click="copyColorValue('rgb')">复制RGB</el-button>
              <el-button type="primary" @click="copyColorValue('hsl')">复制HSL</el-button>
              <el-button type="primary" @click="copyColorValue('cmyk')">复制CMYK</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const activeTab = ref('regex')

// 根据URL参数设置活动标签页
onMounted(() => {
  const tab = route.query.tab
  if (tab && ['regex', 'color'].includes(tab)) {
    activeTab.value = tab
  }
})

// 正则表达式表单
const regexForm = reactive({
  pattern: '',
  testText: '',
  flags: ['g'],
  result: ''
})

// 颜色表单
const colorForm = reactive({
  input: '',
  colorPicker: '#409EFF',
  hex: '',
  rgb: '',
  hsl: '',
  cmyk: ''
})

// 测试正则表达式
const testRegex = () => {
  if (!regexForm.pattern || !regexForm.testText) {
    regexForm.result = ''
    return
  }
  
  try {
    const flags = regexForm.flags.join('')
    const regex = new RegExp(regexForm.pattern, flags)
    const matches = regexForm.testText.match(regex)
    
    if (matches) {
      regexForm.result = `匹配成功！\n找到 ${matches.length} 个匹配项：\n${matches.join('\n')}`
    } else {
      regexForm.result = '未找到匹配项'
    }
  } catch (error) {
    regexForm.result = `正则表达式错误: ${error.message}`
  }
}

// 清空正则表达式
const clearRegex = () => {
  regexForm.pattern = ''
  regexForm.testText = ''
  regexForm.result = ''
}

// 颜色选择器变化
const onColorPickerChange = (color) => {
  colorForm.input = color
  convertColor()
}

// 转换颜色
const convertColor = () => {
  if (!colorForm.input) {
    clearColorForm()
    return
  }
  
  try {
    const color = parseColor(colorForm.input)
    if (color) {
      colorForm.hex = color.hex
      colorForm.rgb = color.rgb
      colorForm.hsl = color.hsl
      colorForm.cmyk = color.cmyk
    } else {
      clearColorForm()
    }
  } catch (error) {
    clearColorForm()
  }
}

// 清空颜色表单
const clearColorForm = () => {
  colorForm.hex = ''
  colorForm.rgb = ''
  colorForm.hsl = ''
  colorForm.cmyk = ''
}

// 解析颜色
const parseColor = (input) => {
  input = input.trim()
  
  // HEX格式
  if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(input)) {
    const hex = input.length === 4 ? 
      '#' + input[1] + input[1] + input[2] + input[2] + input[3] + input[3] : 
      input
    const rgb = hexToRgb(hex)
    return {
      hex: hex.toUpperCase(),
      rgb: `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,
      hsl: rgbToHsl(rgb.r, rgb.g, rgb.b),
      cmyk: rgbToCmyk(rgb.r, rgb.g, rgb.b)
    }
  }
  
  // RGB格式
  const rgbMatch = input.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
  if (rgbMatch) {
    const r = parseInt(rgbMatch[1])
    const g = parseInt(rgbMatch[2])
    const b = parseInt(rgbMatch[3])
    return {
      hex: rgbToHex(r, g, b),
      rgb: `rgb(${r}, ${g}, ${b})`,
      hsl: rgbToHsl(r, g, b),
      cmyk: rgbToCmyk(r, g, b)
    }
  }
  
  // RGBA格式
  const rgbaMatch = input.match(/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/)
  if (rgbaMatch) {
    const r = parseInt(rgbaMatch[1])
    const g = parseInt(rgbaMatch[2])
    const b = parseInt(rgbaMatch[3])
    return {
      hex: rgbToHex(r, g, b),
      rgb: `rgba(${r}, ${g}, ${b}, ${rgbaMatch[4]})`,
      hsl: rgbToHsl(r, g, b),
      cmyk: rgbToCmyk(r, g, b)
    }
  }
  
  return null
}

// HEX转RGB
const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null
}

// RGB转HEX
const rgbToHex = (r, g, b) => {
  return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase()
}

// RGB转HSL
const rgbToHsl = (r, g, b) => {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h, s, l = (max + min) / 2
  
  if (max === min) {
    h = s = 0
  } else {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
    
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }
    h /= 6
  }
  
  return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`
}

// RGB转CMYK
const rgbToCmyk = (r, g, b) => {
  r /= 255
  g /= 255
  b /= 255
  
  const k = 1 - Math.max(r, g, b)
  const c = (1 - r - k) / (1 - k)
  const m = (1 - g - k) / (1 - k)
  const y = (1 - b - k) / (1 - k)
  
  return `cmyk(${Math.round(c * 100)}%, ${Math.round(m * 100)}%, ${Math.round(y * 100)}%, ${Math.round(k * 100)}%)`
}

// 复制颜色值
const copyColorValue = async (type) => {
  let text = ''
  switch (type) {
    case 'hex':
      text = colorForm.hex
      break
    case 'rgb':
      text = colorForm.rgb
      break
    case 'hsl':
      text = colorForm.hsl
      break
    case 'cmyk':
      text = colorForm.cmyk
      break
  }
  
  if (!text) {
    ElMessage.warning('没有颜色值可复制')
    return
  }
  
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (error) {
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}
</script>

<style scoped>
.other-page {
  max-width: 1000px;
  margin: 0 auto;
}

.el-tabs {
  margin-top: 20px;
}
</style> 